local socket = require("socket")
package.path = package.path ..';../?.lua'
local tool = require('lib/tool')

local Linster = tool.class('linster')
function Linster:Ctor()
    self.server = nil;
    self.tbClient ={}
    self.dwConn = 0;
end

function Linster:bind(host, port, timeout)
    self.server = assert(socket.bind(host, port, 1024))
    self.server:settimeout(timeout)
end

function Linster:runServer()
    while true do
        self:onUpdate()
    end
end

function Linster:onUpdate()
    local conn = self.server:accept()
    if conn then
        self:onConnect(conn)
    end

    for conn_count, client in pairs(self.tbClient) do
        local recvt, sendt, status = socket.select({client}, nil, 1)
        if #recvt > 0 then
            local receive, receive_status = client:receive()
            if receive_status ~= "closed" then
                if receive then
                    self:onReceive(client, receive)
                end
            else
                self:onDisConnect(conn_count)
                table.remove(self.tbClient, conn_count)
                client:close()
                -- print("Client " .. conn_count .. " disconnect!")
            end
        end

    end
end

function Linster:onConnect(conn)
    self.dwConn = self.dwConn + 1
    self.tbClient[self.dwConn] = conn
    print("A client successfully connect!")
end

function Linster:onReceive(client, receive)
    error("this func need to be rewrite in subClass")
end

function Linster:process(receive)

end

function Linster:onDisConnect(dwConnIndex)
    -- print("onDisConnect index is ", dwConnIndex)
end

return Linster

